package xyz.zcq.zcqrpc.bootstrap;

import xyz.zcq.zcqrpc.RpcApplication;
import xyz.zcq.zcqrpc.config.RegistryConfig;
import xyz.zcq.zcqrpc.config.RpcConfig;
import xyz.zcq.zcqrpc.model.ServiceMetaInfo;
import xyz.zcq.zcqrpc.model.ServiceRegisterInfo;
import xyz.zcq.zcqrpc.registry.LocalImplRegistry;
import xyz.zcq.zcqrpc.registry.Registry;
import xyz.zcq.zcqrpc.registry.RegistryFactory;
import xyz.zcq.zcqrpc.server.tcp.VertxTcpServer;

import java.util.List;

/**
 * 服务提供者引导程序
 */
public class ProviderBootstrap {

    /**
     * 初始化
     *
     * @param serviceRegisterInfoList 服务注册信息集合
     */
    public static void init(List<ServiceRegisterInfo<?>> serviceRegisterInfoList) {
        // RPC框架初始化
        RpcConfig rpcConfig = RpcApplication.getRpcConfig();

        // 服务注册
        for (ServiceRegisterInfo<?> serviceRegisterInfo : serviceRegisterInfoList) {
            // 注册服务实现到本地
            String serviceName = serviceRegisterInfo.getServiceName();
            LocalImplRegistry.register(serviceName, serviceRegisterInfo.getImplClass());

            // 注册服务到注册中心
            RegistryConfig registryConfig = rpcConfig.getRegistryConfig();
            Registry registry = RegistryFactory.getInstance(registryConfig.getRegistry());
            ServiceMetaInfo serviceMetaInfo = new ServiceMetaInfo();
            serviceMetaInfo.setServiceName(serviceName);
            serviceMetaInfo.setServiceHost(rpcConfig.getServerHost());
            serviceMetaInfo.setServicePort(rpcConfig.getServerPort());
            try {
                registry.register(serviceMetaInfo);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        // 启动Web服务
        new VertxTcpServer().doStart(rpcConfig.getServerPort());
    }

}
